<template>
  <div class="payment-approval-list">
    <h2>付款审批列表</h2>

    <!-- 查询条件 -->
    <div class="search-form">
      <div class="form-row">
        <label>标题：</label>
        <input v-model="searchForm.title" placeholder="请输入标题" />
      </div>
      <div class="form-row">
        <label>申请人：</label>
        <input v-model="searchForm.requester" placeholder="请输入申请人" />
      </div>
      <div class="form-row">
        <label>审批状态：</label>
        <select v-model="searchForm.approvalStatus">
          <option value="">全部</option>
          <option value="0">待审批</option>
          <option value="1">已通过</option>
          <option value="2">已拒绝</option>
        </select>
      </div>
      <div class="form-row">
        <label>付款日期：</label>
        <input type="date" v-model="searchForm.paymentDateStart" />
        <span>至</span>
        <input type="date" v-model="searchForm.paymentDateEnd" />
      </div>
      <div class="form-row">
        <button @click="onSearch">查询</button>
        <button @click="onReset">重置</button>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="alert error-alert">{{ error }}</div>

    <!-- 数据表格 -->
    <table class="table">
      <thead>
        <tr>
          <th>标题</th>
          <th>用途描述</th>
          <th>付款金额</th>
          <th>付款方式</th>
          <th>支付对象</th>
          <th>申请人</th>
          <th>付款日期</th>
          <th>轮次</th>
          <th>审批状态</th>
          <th>审批人</th>
          <th>审批时间</th>
          <th>审批意见</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in paymentList" :key="item.processDetailCode || item.id">
          <td>{{ item.title }}</td>
          <td>{{ item.usageDescription }}</td>
          <td>{{ formatAmount(item.paymentAmount) }}</td>
          <td>{{ item.paymentMethod }}</td>
          <td>{{ item.payee }}</td>
          <td>{{ item.requester }}</td>
          <td>{{ item.paymentDate ? formatDate(item.paymentDate) : '-' }}</td>
          <td>{{ item.roundNo ?? 0 }}</td>
          <td>
            <span class="status-chip" :class="getDetailStatusClass(resolveDetailState(item))">
              {{ getDetailStatusText(resolveDetailState(item)) }}
            </span>
          </td>
          <td>{{ item.currentApproverName || '-' }}</td>
          <td>{{ item.pdApprovalTime ? formatDate(item.pdApprovalTime) : '-' }}</td>
          <td>{{ item.pdApprovalComments || '-' }}</td>
          <td>
            <button @click="onViewDetails(item)">查看详情</button>
          </td>
        </tr>
        <tr v-if="!loading && paymentList.length === 0">
          <td colspan="13" class="empty">暂无数据</td>
        </tr>
      </tbody>
    </table>

    <!-- 预测/训练 操作 -->
    <div class="predict-actions" style="margin:12px 0; display:flex; gap:10px;">
      <button @click="onAppendForecast" title="将最新数据在线追加到最新模型">在线追加</button>
      <button @click="onPredictForecast" title="预测未来7天审批次数">预测未来7天</button>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <div class="page-size">
        <span>每页</span>
        <div class="page-size-group">
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 10 }" @click="setPageSize(10)">10</button>
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 20 }" @click="setPageSize(20)">20</button>
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 50 }" @click="setPageSize(50)">50</button>
        </div>
      </div>
      <div class="pager-controls">
        <button @click="onPrevPage" :disabled="currentPage <= 1">上一页</button>
        <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
        <button @click="onNextPage" :disabled="currentPage >= totalPages">下一页</button>
      </div>
    </div>

    <!-- 审批详情弹窗 -->
    <div v-if="detailDialog.visible" class="dialog-mask">
      <div class="dialog large">
        <h3>付款审批详情</h3>
        
        <!-- 基本信息展示 -->
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-content">
            <div class="detail-row">
              <label>标题：</label>
              <span>{{ currentItem?.title }}</span>
            </div>
            <div class="detail-row">
              <label>用途描述：</label>
              <span>{{ currentItem?.usageDescription }}</span>
            </div>
            <div class="detail-row">
              <label>付款金额：</label>
              <span>{{ currentItem?.paymentAmount ? `¥${currentItem.paymentAmount.toFixed(2)}` : '-' }}</span>
            </div>
            <div class="detail-row">
              <label>付款方式：</label>
              <span>{{ currentItem?.paymentMethod }}</span>
            </div>
            <div class="detail-row">
              <label>支付对象：</label>
              <span>{{ currentItem?.payee }}</span>
            </div>
            <div class="detail-row">
              <label>申请人：</label>
              <span>{{ currentItem?.requester }}</span>
            </div>
            <div class="detail-row">
              <label>付款日期：</label>
              <span>{{ currentItem?.paymentDate ? formatDate(currentItem.paymentDate) : '-' }}</span>
            </div>
            <div class="detail-row">
              <label>审批状态：</label>
              <span :class="getDetailStatusClass(resolveDetailState(currentItem!))">
                {{ getDetailStatusText(resolveDetailState(currentItem!)) }}
              </span>
            </div>
          </div>
        </div>

        <!-- 审批操作表单（仅当前审批人可见） -->
        <div v-if="(resolveDetailState(currentItem!) === null || resolveDetailState(currentItem!) === undefined) && canApprove" class="approval-section">
          <h4>审批操作</h4>
          <div class="approval-form">
            <div class="form-row">
              <label>审批备注：</label>
              <textarea v-model="approvalForm.remarks" placeholder="请输入备注信息" rows="3"></textarea>
            </div>
            <div class="form-row">
              <label>转批人：</label>
              <div class="transfer-input">
                <input v-model="approvalForm.transferTo" placeholder="请输入转批人编号" readonly />
                <button type="button" class="select-user-btn" @click="onSelectTransferUser">选择</button>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="approval-actions">
            <button class="approve-transfer-btn" @click="onApproveAndTransfer">通过并转批</button>
            <button class="reject-btn" @click="onReject">拒绝</button>
            <button class="approve-terminate-btn" @click="onApproveAndTerminate">通过并终止审批</button>
          </div>
        </div>

        <!-- 审批历史信息 -->
        <div v-if="resolveDetailState(currentItem!) !== null && resolveDetailState(currentItem!) !== undefined" class="history-section">
          <h4>审批结果</h4>
          <div class="detail-content">
            <div class="detail-row">
              <label>审批状态：</label>
              <span :class="getDetailStatusClass(resolveDetailState(currentItem!))">
                {{ getDetailStatusText(resolveDetailState(currentItem!)) }}
              </span>
            </div>
            <div class="detail-row">
              <label>审批人：</label>
              <span>{{ currentItem?.currentApproverName || '-' }}</span>
            </div>
            <div class="detail-row">
              <label>审批时间：</label>
              <span>{{ currentItem?.approvalTime ? formatDate(currentItem.approvalTime) : '-' }}</span>
            </div>
            <div class="detail-row">
              <label>审批意见：</label>
              <span>{{ currentItem?.approvalComments || currentItem?.approvalRemark || '-' }}</span>
            </div>
            <div v-if="resolveDetailState(currentItem!) === 1 && currentItem?.recommender" class="detail-row">
              <label>转批给：</label>
              <span>{{ currentItem?.recommender }}</span>
            </div>
          </div>
        </div>

        <div class="dialog-actions">
          <button class="plain" @click="detailDialog.visible = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 用户选择弹窗 -->
    <div v-if="userSelectDialog.visible" class="dialog-mask">
      <div class="dialog large">
        <h3>选择转批人</h3>
        
        <!-- 用户搜索 -->
        <div class="user-search">
          <input v-model="userSearchForm.keyword" placeholder="请输入用户名或账号搜索" @input="onUserSearch" />
          <button @click="onUserSearch">搜索</button>
        </div>
        
        <!-- 用户列表 -->
        <div class="user-list">
          <div v-if="userList.length === 0" class="no-data">暂无用户数据</div>
          <div v-else class="user-items">
            <div 
              v-for="user in userList" 
              :key="user.id" 
              class="user-item"
              :class="{ selected: selectedTransferUser?.id === user.id }"
              @click="onSelectUser(user)"
            >
              <div class="user-info">
                <div class="user-name">{{ user.nickname || user.account || '未知用户' }}</div>
                <div class="user-account">{{ user.account || user.id }}</div>
              </div>
              <div v-if="selectedTransferUser?.id === user.id" class="selected-icon">✓</div>
            </div>
          </div>
        </div>
        
        <div class="dialog-actions">
          <button class="plain" @click="userSelectDialog.visible = false">取消</button>
          <button @click="onConfirmTransferUser" :disabled="!selectedTransferUser">确定</button>
        </div>
      </div>
    </div>

    <!-- 预测结果弹窗 -->
    <div v-if="predictDialog.visible" class="dialog-mask">
      <div class="dialog">
        <h3>未来7天审批次数预测</h3>
        <div v-if="predictLoading" class="loading">加载中...</div>
        <div v-else>
          <table class="table">
            <thead>
              <tr>
                <th>日期</th>
                <th>预测值</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="it in predictItems" :key="it.Date">
                <td>{{ formatDate(it.Date) }}</td>
                <td>{{ it.Forecast }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="dialog-actions">
          <button class="plain" @click="predictDialog.visible=false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 加载覆盖层 -->
    <div v-if="loading" class="loading-overlay">
      <div class="spinner"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import { useCounterStore } from '@/stores/counter'
import { examineApi } from '@/api'

type PaymentApprovalItem = {
  id: number
  title: string
  usageDescription: string
  paymentAmount?: number
  paymentMethod: string
  payee: string
  requester: string
  paymentDate?: string
  roundNo?: number | null
  approvalStatus: number
  approvalByName?: string
  approvalTime?: string
  approvalComments?: string
  pdApprovalTime?: string
  pdApprovalComments?: string
  processDetailCode?: string
  approveCode?: string | number
  typeCode?: string
  submittedTime?: string
  submittedByName?: string
  currentApproverCode?: string
  currentApproverName?: string
  approvalRemark?: string
  recommender?: string
  detailState?: number | null
}

type UserItem = {
  id: number
  nickname?: string
  account?: string
}

const paymentList = ref<PaymentApprovalItem[]>([])
const currentPage = ref(1)
const totalPages = ref(1)
const pageSize = ref(10)

const searchForm = reactive({
  title: '',
  requester: '',
  approvalStatus: '',
  paymentDateStart: '',
  paymentDateEnd: ''
})

const detailDialog = reactive({
  visible: false
})

const currentItem = ref<PaymentApprovalItem | null>(null)

const approvalForm = reactive({
  remarks: '',
  transferTo: ''
})

const counts = useCounterStore()
const currentUserCode = String(counts.Logins.UserId || counts.Logins.Account || '1')

// 仅当前审批人可进行交互
const canApprove = computed(() => {
  if (!currentItem.value) return false
  const state = resolveDetailState(currentItem.value)
  if (!(state === null || state === undefined)) return false
  const approver = String(currentItem.value.currentApproverCode || '')
  return !!approver && approver === currentUserCode
})
const isSubmitting = ref(false)

// 用户选择相关状态
const userSelectDialog = reactive({
  visible: false
})

const userList = ref<UserItem[]>([])
const disabledTransferIds = ref<Set<string>>(new Set())
const selectedTransferUser = ref<UserItem | null>(null)
const userSearchForm = reactive({
  keyword: ''
})

const loading = ref(false)
const error = ref('')

// 预测弹窗
const predictDialog = reactive({ visible: false })
const predictLoading = ref(false)
const predictItems = ref<{ Date: string; Forecast: number }[]>([])

async function loadPaymentList() {
  loading.value = true
  error.value = ''
  try {
    const params: any = {
      pageindex: currentPage.value,
      pageSize: pageSize.value
    }

    if (searchForm.title) params.title = searchForm.title
    if (searchForm.requester) params.requester = searchForm.requester
    if (searchForm.approvalStatus) params.approvalStatus = parseInt(searchForm.approvalStatus)
    if (searchForm.paymentDateStart) params.paymentDateStart = searchForm.paymentDateStart
    if (searchForm.paymentDateEnd) params.paymentDateEnd = searchForm.paymentDateEnd

    const res = await examineApi.getPaymentApprovalList(params)
    console.log('API响应:', res) // 调试日志
    const container: any = (res && (res as any).data) ? (res as any).data : res
    const data: any[] = Array.isArray(container?.data)
      ? container.data
      : (Array.isArray(container?.Data) ? container.Data : (Array.isArray(container) ? container : []))
    console.log('数据列表:', data) // 调试日志
    console.log('第一条数据的字段:', data[0]) // 调试第一条数据的字段
    
    const mappedList: PaymentApprovalItem[] = data.map((x: any) => ({
      id: x.id ?? x.Id ?? 0,
      title: x.title ?? x.Title ?? '',
      usageDescription: x.usageDescription ?? x.UsageDescription ?? '',
      paymentAmount: x.paymentAmount ?? x.PaymentAmount,
      paymentMethod: x.paymentMethod ?? x.PaymentMethod ?? '',
      payee: x.payee ?? x.Payee ?? '',
      requester: x.requester ?? x.Requester ?? '',
      paymentDate: x.paymentDate ?? x.PaymentDate,
      roundNo: x.roundNo ?? x.RoundNo ?? null,
      approvalStatus: x.approvalStatus ?? x.ApprovalStatus ?? 0,
      approvalByName: x.currentApproverCode ?? x.CurrentApproverCode,
      approvalTime: x.approvalTime ?? x.ApprovalTime,
      approvalComments: x.approvalComments ?? x.ApprovalComments,
      processDetailCode: x.processDetailCode ?? x.ProcessDetailCode,
      approveCode: x.approveCode ?? x.ApproveCode ?? x.businessId ?? x.BusinessId,
      typeCode: x.typeCode ?? x.TypeCode ?? x.businessType ?? x.BusinessType,
      submittedTime: x.submittedTime ?? x.SubmittedTime,
      submittedByName: x.submittedByName ?? x.SubmittedByName,
      currentApproverCode: x.currentApproverCode ?? x.CurrentApproverCode,
      currentApproverName: x.currentApproverName ?? x.CurrentApproverName,
      approvalRemark: x.approvalRemark ?? x.ApprovalRemark,
      pdApprovalTime: x.pdApprovalTime ?? x.PDApprovalTime,
      pdApprovalComments: x.pdApprovalComments ?? x.PDApprovalComments,
      recommender: x.recommender ?? x.Recommender,
      detailState: x.detailState ?? x.DetailState ?? x.currentApprovalState ?? x.CurrentApprovalState
    }))

    // 去重：按 processDetailCode 去重，优先保留待审批（detailState=null）的那条
    const dedupMap = new Map<string, PaymentApprovalItem>()
    for (const item of mappedList) {
      const key = item.processDetailCode || ''
      if (!key) {
        // 没有明细编号则直接保留（极端情况）
        paymentList.value.push(item)
        continue
      }
      if (!dedupMap.has(key)) {
        dedupMap.set(key, item)
      } else {
        const kept = dedupMap.get(key) as PaymentApprovalItem
        const keptIsPending = kept.detailState === null || kept.detailState === undefined
        const curIsPending = item.detailState === null || item.detailState === undefined
        if (!keptIsPending && curIsPending) {
          dedupMap.set(key, item)
        }
      }
    }

    paymentList.value = Array.from(dedupMap.size ? dedupMap.values() : mappedList)

    // 不再进行兜底推断，直接使用后端返回的状态

    console.log('映射后的列表:', paymentList.value) // 调试日志
    console.log('第一条映射后的数据:', paymentList.value[0]) // 调试第一条映射后的数据
    const totalCount = container?.TotalCount ?? container?.totalCount ?? container?.Total ?? paymentList.value.length
    totalPages.value = container?.TotalPage ?? container?.totalPage ?? Math.max(1, Math.ceil((Number(totalCount) || 0) / pageSize.value))
  } catch (e) {
    console.error('加载付款审批列表失败', e)
    error.value = '加载失败'
  }
  finally {
    loading.value = false
  }
}

function onSearch() {
  currentPage.value = 1
  loadPaymentList()
}

function onReset() {
  searchForm.title = ''
  searchForm.requester = ''
  searchForm.approvalStatus = ''
  searchForm.paymentDateStart = ''
  searchForm.paymentDateEnd = ''
  currentPage.value = 1
  loadPaymentList()
}

function onPrevPage() {
  if (currentPage.value > 1) {
    currentPage.value--
    loadPaymentList()
  }
}

function onNextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    loadPaymentList()
  }
}

function onPageSizeChange() {
  currentPage.value = 1
  loadPaymentList()
}

function setPageSize(size: number) {
  if (pageSize.value === size) return
  pageSize.value = size
  onPageSizeChange()
}

function onViewDetails(item: PaymentApprovalItem) {
  currentItem.value = item
  // 重置审批表单
  approvalForm.remarks = ''
  approvalForm.transferTo = ''
  detailDialog.visible = true
}

function onApproval(item: PaymentApprovalItem) {
  onViewDetails(item) // 复用详情弹窗
}

async function onSelectTransferUser() {
  // 打开用户选择弹窗
  userSelectDialog.visible = true
  selectedTransferUser.value = null
  userSearchForm.keyword = ''
  await loadUsers()
}

async function loadUsers() {
  try {
    const res = await examineApi.getUsers({})
    console.log('用户列表API响应:', res)
    const data = res.data?.data || []
    userList.value = data.map((x: any) => ({
      id: x.id ?? x.Id ?? 0,
      nickname: x.nickname ?? x.Nickname ?? '',
      account: x.account ?? x.Account ?? ''
    }))
    console.log('映射后的用户列表:', userList.value)
    await buildDisabledTransferSet()
  } catch (e) {
    console.error('加载用户列表失败', e)
    userList.value = []
  }
}

function onUserSearch() {
  // 这里可以实现搜索逻辑，暂时重新加载所有用户
  loadUsers()
}

function onSelectUser(user: UserItem) {
  if (disabledTransferIds.value.has(String(user.id))) return
  selectedTransferUser.value = user
}

function onConfirmTransferUser() {
  if (selectedTransferUser.value) {
    // 将选中的用户ID设置为转批人
    approvalForm.transferTo = selectedTransferUser.value.id.toString()
    userSelectDialog.visible = false
  }
}

// 构建禁用的转批人集合：预设内审批人 + 本轮已转批过的人 + 当前审批人
async function buildDisabledTransferSet() {
  try {
    const set = new Set<string>()
    if (!currentItem.value) { disabledTransferIds.value = set; return }
    const approveCode = String(currentItem.value.approveCode || '')
    const nodeCode = String((currentItem.value as any).nodeCode || '')
    const roundNo = currentItem.value.roundNo ?? null

    // 预设内审批人：当前实现缺少流程编号上下文，暂时仅使用已加载的付款列表无法可靠取到，后续按需扩展

    // 已转批人（当前轮）
    const res2 = await examineApi.getTransferredApproverList({ approveCode, nodeCode: nodeCode || undefined, roundNo: roundNo ?? undefined })
    const transferred: string[] = Array.isArray(res2?.data?.data) ? res2.data.data : []

    // 当前审批人
    const cur = String(currentItem.value.currentApproverCode || '')

    transferred.forEach(id => { const v = String(id).trim(); if (v) set.add(v) })
    if (cur) set.add(cur)

    disabledTransferIds.value = set
  } catch (e) {
    console.warn('构建禁用转批人集合失败', e)
    disabledTransferIds.value = new Set()
  }
}

function isCurrentApprover(item: PaymentApprovalItem): boolean {
  return (item.currentApproverCode || currentUserCode) === currentUserCode
}

async function onApproveAndTransfer() {
  if (!currentItem.value) return
  
  try {
    isSubmitting.value = true
    const payload = {
      ProcessDetailCode: currentItem.value.processDetailCode || '',
      ApproverCode: String(currentUserCode), // 使用当前登录用户ID
      Approve: true,
      Transfer: true,
      TransferTo: String(approvalForm.transferTo || ''),
      Remark: String(approvalForm.remarks || ''),
      ModifiedBy: String(counts.Logins.Nickname || counts.Logins.Account || currentUserCode)
    }
    
    console.log('提交审批数据:', payload) // 调试日志
    await examineApi.submitProcessDetail(payload)
    // 乐观更新：仅更新当前明细的状态
    const code = currentItem.value.processDetailCode
    currentItem.value.detailState = 1
    currentItem.value.recommender = approvalForm.transferTo || currentItem.value.recommender
    const idx = paymentList.value.findIndex(x => x.processDetailCode === code)
    if (idx !== -1) {
      paymentList.value[idx] = { ...paymentList.value[idx], detailState: 1, recommender: currentItem.value.recommender }
    }
    detailDialog.visible = false
    await loadPaymentList()
  } catch (e) {
    console.error('通过并转批失败', e)
  } finally {
    isSubmitting.value = false
  }
}

async function onReject() {
  if (!currentItem.value) return
  
  try {
    isSubmitting.value = true
    const payload = {
      ProcessDetailCode: currentItem.value.processDetailCode || '',
      ApproverCode: String(currentUserCode), // 使用当前登录用户ID
      Approve: false,
      Transfer: false,
      TransferTo: '',
      Remark: String(approvalForm.remarks || ''),
      ModifiedBy: String(counts.Logins.Nickname || counts.Logins.Account || currentUserCode)
    }
    
    console.log('提交审批数据:', payload) // 调试日志
    await examineApi.submitProcessDetail(payload)
    // 乐观更新：仅更新当前明细的状态
    const code = currentItem.value.processDetailCode
    currentItem.value.detailState = 2
    const idx = paymentList.value.findIndex(x => x.processDetailCode === code)
    if (idx !== -1) {
      paymentList.value[idx] = { ...paymentList.value[idx], detailState: 2 }
    }
    detailDialog.visible = false
    await loadPaymentList()
  } catch (e) {
    console.error('拒绝失败', e)
  } finally {
    isSubmitting.value = false
  }
}

async function onApproveAndTerminate() {
  if (!currentItem.value) return
  
  try {
    isSubmitting.value = true
    const payload = {
      ProcessDetailCode: currentItem.value.processDetailCode || '',
      ApproverCode: String(currentUserCode), // 使用当前登录用户ID
      Approve: true,
      Transfer: false,
      TransferTo: '', // 清空转批人
      Remark: String(approvalForm.remarks || ''),
      ModifiedBy: String(counts.Logins.Nickname || counts.Logins.Account || currentUserCode)
    }
    
    console.log('提交审批数据:', payload) // 调试日志
    await examineApi.submitProcessDetail(payload)
    // 乐观更新：仅更新当前明细的状态
    const code = currentItem.value.processDetailCode
    currentItem.value.detailState = 1
    const idx = paymentList.value.findIndex(x => x.processDetailCode === code)
    if (idx !== -1) {
      paymentList.value[idx] = { ...paymentList.value[idx], detailState: 1 }
    }
    detailDialog.visible = false
    await loadPaymentList()
  } catch (e) {
    console.error('通过并终止审批失败', e)
  } finally {
    isSubmitting.value = false
  }
}

function getStatusText(status: number | undefined): string {
  switch (status) {
    case 0: return '待审批'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

function getStatusClass(status: number | undefined): string {
  switch (status) {
    case 0: return 'status-pending'
    case 1: return 'status-approved'
    case 2: return 'status-rejected'
    default: return 'status-unknown'
  }
}

function getDetailStatusText(state: number | null | undefined): string {
  if (state === null || state === undefined) return '待审批'
  switch (state) {
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '处理中'
  }
}

function getDetailStatusClass(state: number | null | undefined): string {
  if (state === null || state === undefined) return 'status-pending'
  switch (state) {
    case 1: return 'status-approved'
    case 2: return 'status-rejected'
    default: return 'status-unknown'
  }
}

function resolveDetailState(item: PaymentApprovalItem): number | null | undefined {
  // 优先使用 detailState（即 pd.State）
  if (item.detailState !== null && item.detailState !== undefined) {
    return item.detailState
  }
  // 如果 detailState 为空，返回 null（待审批）
  return null
}

function formatDate(dateStr: string): string {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

function formatAmount(value?: number): string {
  const n = Number(value)
  if (Number.isFinite(n)) return `¥${n.toFixed(2)}`
  return '-'
}

onMounted(() => {
  loadPaymentList()
})

// 在线追加（T006）
async function onAppendForecast() {
  try {
    loading.value = true
    await examineApi.approvalForecastAppend({ typeCode: 'T006' })
    alert('已追加最新数据到模型(T006)')
  } catch (e) {
    console.error('在线追加失败', e)
    alert('在线追加失败')
  } finally {
    loading.value = false
  }
}

// 预测（T006）
async function onPredictForecast() {
  try {
    predictDialog.visible = true
    predictLoading.value = true
    const res = await examineApi.approvalForecastPredict({ typeCode: 'T006' })
    // 后端返回结构：{ code, message, data: { Items: [...] } }
    const payload: any = (res as any)?.data || {}
    const list = Array.isArray(payload.Items) ? payload.Items : (Array.isArray(payload.items) ? payload.items : [])
    predictItems.value = list.map((x:any) => ({
      Date: x.Date ?? x.date ?? x.PredictDate ?? x.predictDate,
      Forecast: Number(x.Forecast ?? x.forecast ?? x.Value ?? x.value ?? 0)
    }))
  } catch (e) {
    console.error('预测失败', e)
    predictItems.value = []
    alert('预测失败，请先训练或检查服务配置')
  } finally {
    predictLoading.value = false
  }
}
</script>

<style scoped>
.payment-approval-list {
  padding: 20px;
}

.search-form {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-row label {
  font-weight: bold;
  min-width: 80px;
}

.form-row input,
.form-row select,
.form-row textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-row textarea {
  width: 300px;
  height: 80px;
  resize: vertical;
}

.table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #ddd;
  padding: 12px 8px;
  text-align: left;
  font-size: 12px;
}

.table th {
  background: #f5f5f5;
  font-weight: bold;
}

.table tbody tr:hover {
  background: #f9f9f9;
}

.status-chip { display:inline-block; padding: 4px 10px; border-radius: 999px; font-weight: 600; font-size: 12px; }
/* 更鲜明的颜色区分 */
.status-pending { color:#b45309; background:#fffbeb; border:1px solid #f59e0b; }
.status-approved { color:#065f46; background:#ecfdf5; border:1px solid #10b981; }
.status-rejected { color:#991b1b; background:#fef2f2; border:1px solid #ef4444; }
.status-unknown { color:#1f2937; background:#f3f4f6; border:1px solid #e5e7eb; }

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.pagination .page-size { display:flex; align-items:center; gap:8px; }
.page-size-group { display:inline-flex; background:#f0f2f5; border:1px solid #d9d9d9; border-radius:999px; padding:2px; }
.page-size-pill { border:none; background:transparent; padding:6px 12px; border-radius:999px; cursor:pointer; font-size:12px; color:#606266; }
.page-size-pill.active { background:#fff; color:#303133; border:1px solid #d9d9d9; }
.pager-controls { display:flex; align-items:center; gap:10px; }

.pagination button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  background: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 8px;
  padding: 20px;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.dialog.large {
  max-width: 900px;
}

.dialog h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-row {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.detail-row label {
  font-weight: bold;
  min-width: 100px;
  color: #666;
}

.detail-row span {
  flex: 1;
  word-break: break-all;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.dialog-actions button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-actions button:not(.plain) {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.dialog-actions button.plain {
  background: white;
  color: #666;
}

/* 通用警告/错误样式 */
.alert { padding: 12px 14px; border-radius: 6px; margin: 12px 0; }
.error-alert { background: #fff2f0; color: #a8071a; border: 1px solid #ffa39e; }

/* 加载覆盖层 */
.loading-overlay {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(255,255,255,0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.spinner {
  width: 44px;
  height: 44px;
  border: 4px solid #e0e0e0;
  border-top-color: #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:hover {
  background: #f5f5f5;
}

button.danger {
  background: #dc3545;
  color: white;
  border-color: #dc3545;
}

button.danger:hover {
  background: #c82333;
}

/* 审批表单样式 */
.detail-section,
.approval-section,
.history-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background: #fafafa;
}

.detail-section h4,
.approval-section h4,
.history-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
}

.approval-form {
  margin-bottom: 20px;
}

.approval-form .form-row {
  margin-bottom: 15px;
}

.approval-form label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #333;
}

.approval-form textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  resize: vertical;
}

.transfer-input {
  display: flex;
  gap: 8px;
  align-items: center;
}

.transfer-input input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.select-user-btn {
  padding: 8px 12px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.select-user-btn:hover {
  background: #0056b3;
}

.approval-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.approve-transfer-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
}

.approve-transfer-btn:hover {
  background: #0056b3;
}

.reject-btn {
  background: white;
  color: #dc3545;
  border: 2px solid #dc3545;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
}

.reject-btn:hover {
  background: #dc3545;
  color: white;
}

.approve-terminate-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
}

.approve-terminate-btn:hover {
  background: #1e7e34;
}

/* 用户选择弹窗样式 */
.user-search {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.user-search input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.user-search button {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.user-search button:hover {
  background: #0056b3;
}

.user-list {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 14px;
}

.user-items {
  display: flex;
  flex-direction: column;
}

.user-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-item:last-child {
  border-bottom: none;
}

.user-item:hover {
  background: #f8f9fa;
}

.user-item.selected {
  background: #e3f2fd;
  border-left: 3px solid #2196f3;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.user-account {
  font-size: 12px;
  color: #666;
}

.selected-icon {
  color: #2196f3;
  font-weight: bold;
  font-size: 16px;
}
</style>
